/**
 * 成员管理弹层-Code业务封装
 */

import React from 'react';
import PropTypes from 'prop-types';
import MemberDialog from './member';
import './index.scss';

export default class CodeMemberList extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    // 传递类型: project/group
    pathResourceType: PropTypes.string,
    pathResourceId: PropTypes.number,
    title: PropTypes.string,
    onChange: PropTypes.func,
    onAddMembers: PropTypes.func,
    role: PropTypes.string.isRequired,
    // 是否是管理员（列表有成员管理权限的都是管理员）
    isAdmin: PropTypes.bool,
    // 顶级路径ID（列表无pathResource，传入 库用namespace_id 组用parent_id）
    parentId: PropTypes.number,
  };

  static defaultProps = {
    trigger: null,
    pathResourceType: 'project',
    pathResourceId: null,
    title: null,
    onChange: null,
    onAddMembers: null,
    isAdmin: false,
    parentId: null,
  };

  state = {
    visible: false,
  };

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      visible: props.visible,
    };
  }

  toggleVisible = () => {
    this.setState({
      visible: !this.state.visible,
    });
  };

  render() {
    const { visible } = this.state;

    return (
      <React.Fragment>
        {this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              e.preventDefault();
              e.stopPropagation();
              this.toggleVisible();
            },
          })}
        {visible && (
          <MemberDialog
            {...this.props}
            visible={visible}
            onClose={this.props.onClose || this.toggleVisible}
          />
        )}
      </React.Fragment>
    );
  }
}
